﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http.Filters;
using System.Web.Mvc;
using MKAdmin.ToolKit;

namespace MKAdmin.Web.Filters
{
    public class ApiErrorHandler : ExceptionFilterAttribute
    {
        /// <summary>
        /// 异常处理
        /// </summary>
        /// <param name="context"></param>
        public override void OnException(HttpActionExecutedContext context)
        {
            HttpResponseMessage response = null;
            var content = new { msg = "100004" };
            string jsonContent = JsonConvert.SerializeObject(content);
            response.Content = new StringContent(jsonContent, Encoding.GetEncoding("UTF-8"), "application/json");

            response = new HttpResponseMessage(HttpStatusCode.InternalServerError);

            //日志记录
            LogHelper.Error(context.Exception.ToString());

            //可以发送邮件通知相关人员网站发生异常了
            //Helpers.SendEmail("网站异常(ApiError)", context.Exception.ToString());
            //发送邮件
            EmailHelper.Send(new EmailHelper.MailInfo()
            {
                Async = false,
                Body = context.Exception.ToString(),
                Subject = "网站访问异常",
                To = new List<string>() { "mikexu.it@gmail.com" },
                IsBodyHtml = true
            });

            context.Response = response;
        }
    }
}